﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RATSharpW7.ViewModel;
using System.Windows.Navigation;
using RATSharp.Model;
using Microsoft.Phone.Shell;
using System.Diagnostics;
using RATSharpW7.ViewModel.CalendarViewModel;

namespace RATSharpW7.View
{
    /// <summary>
    /// List of all not returned items. 
    /// violates return action on period select.
    /// </summary>
    public partial class ReturnItBack : PhoneApplicationPage
    {
        bool isNewPageInstance = false;
        public ReturnItBackViewModel model { get; set; }

        public ReturnItBack()
        {
            InitializeComponent();
            isNewPageInstance = true;
        }

        private void periodsListbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                // get item from ListBox and store in class var. Store page to navigate to in class var.
                RATSharp.Model.period selectedItem = (RATSharp.Model.period)e.AddedItems[0];
                // reset selection of ListBox
                ((ListBox)sender).SelectedIndex = -1;
                model.returnItem(selectedItem, new EventHandler(objectReturnedHandler));

            }
        }


        public void objectReturnedHandler(object sender, EventArgs args)
        {
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode !=
                  System.Windows.Navigation.NavigationMode.Back)
            {
                State["ReturnItBackViewModel"] = model;
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (isNewPageInstance)
            {
                if (model == null)
                {
                    if (State.ContainsKey("ReturnItBackViewModel"))
                    {
                        model = State["ReturnItBackViewModel"]
                                           as ReturnItBackViewModel;
                    }
                    else
                    {
                        model = new ReturnItBackViewModel();
                    }
                }
            }
            DataContext = model;
            model.loadNotReturnedItems();

            isNewPageInstance = false;
        }
    }
}